package com.cande.loki.aspect;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Author WGF
 * @Date 2021/4/27 17:01
 * @Desc
 */
@Aspect
@Component
public class LogInfoAspect {
    private static final Logger log = LoggerFactory.getLogger(LogInfoAspect.class.getName());// slf4j日志记录器
    //还行符
    private  static  final String LINE_SEPARATOR = System.lineSeparator();

    //以自定义的LogInfo注解为切点
    @Pointcut("@annotation(com.cande.loki.aspect.LogInfo)")
    public void webLog(){}

    /**
     * 切点之前执行
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        //
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取注解LogInfo的描述信息
        String metDesc = getAspectLogDescription(joinPoint);

        //打印请求相关参数
        log.info("---------------------------START---------------------------");
        //打印请求url
        log.info("URL             : {}",request.getRequestURL().toString());
        //打印描述信息
        log.info("Description     : {}",metDesc);
        //打印Http method
        log.info("HTTP method     : {}",request.getMethod());
        //打印调用controller得全路径以及执行方法
        log.info("Calss Method    : {}.{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        //打印请求ip
        log.info("IP              : {}",request.getRemoteAddr());
        //打印请求入参
        log.info("Request Args    : {}" , new Gson().toJson(joinPoint.getArgs()));

    }


    @After("webLog()")
    public void doAfter() {

    }


    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();

        //打印出参
        log.info("Response Args   : {}",new Gson().toJson(result));
        //执行耗时
        log.info("Time-Consuming  : {} ms",System.currentTimeMillis() -startTime);
        //接口结束
        log.info("--------------------------------END--------------------------"+LINE_SEPARATOR);
        return result;
    }

    /**
     * 通过反射获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     */
    public String getAspectLogDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(LogInfo.class).desc());
                    break;
                }
            }
        }
        return description.toString();
    }

}
